package org.example.algorithm.backtracking;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LetterCombinationsSolution {

    public static void main(String[] args) {
        String digits = "23";
        LetterCombinationsSolution solution = new LetterCombinationsSolution();
        List<String> list = solution.letterCombinations(digits);
        System.out.println(list);
    }

    public List<String> letterCombinations(String digits) {
        if (digits.isEmpty()) {
            return new ArrayList<>();
        }
        Map<Character, String> numMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        List<String> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        backCombine(res, numMap, digits, 0, sb);
        return res;
    }

    private void backCombine(List<String> res, Map<Character, String> numMap, String digits, int index, StringBuilder sb) {
        if (index == digits.length()) {
            res.add(sb.toString());
        } else {
            Character num = digits.charAt(index);
            String str = numMap.get(num);
            for (int i=0;i<str.length();i++) {
                sb.append(str.charAt(i));
                backCombine(res, numMap, digits, index+1, sb);
                sb.deleteCharAt(index);
            }
        }
    }
}
